#include <header.h>

int main(){

    char *port = "8080";
    char *ip = "192.168.233.128";
    int socket_fd = socket(AF_INET,SOCK_STREAM,0);
    struct sockaddr_in sockaddr;
    sockaddr.sin_family = AF_INET;
    sockaddr.sin_port = htons(atoi(port));
    sockaddr.sin_addr.s_addr = inet_addr(ip);


    bind(socket_fd,(struct sockaddr *)&sockaddr,sizeof(sockaddr));
    listen(socket_fd,10);

    fd_set base_set;
    FD_ZERO(&base_set);
    FD_SET(socket_fd,&base_set);

    int nat_fd = 0;

    while(1){
        fd_set set;
        memcpy(&set,&base_set,sizeof(base_set));
        select(10,&set,NULL,NULL,NULL);

        if(FD_ISSET(socket_fd,&set)){
            //int nat_fd = accept(socket_fd,NULL,NULL);
            nat_fd = accept(socket_fd,NULL,NULL);
            printf("30 \n");
            FD_CLR(socket_fd,&base_set);
            FD_SET(nat_fd,&base_set);
            FD_SET(STDIN_FILENO,&base_set);
        }
        if(FD_ISSET(nat_fd,&set)){
            printf("35 \n");
            char buf[100] = {0};
            ssize_t ret = recv(nat_fd,buf,sizeof(buf),0);
            if(ret == 0){
                FD_CLR(nat_fd,&base_set);
                FD_SET(socket_fd,&base_set);
                continue;

            }
            printf("buf: %s \n", buf);
        }
        if(FD_ISSET(STDIN_FILENO,&set)){
            printf("49 \n");
            char buf[100] = {0};
            ssize_t ret = read(STDIN_FILENO,buf,sizeof(buf));
            send(nat_fd,buf,ret,0);
        }

    }        


    close(socket_fd);
    close(nat_fd);
    return 0;
}

